package com.sky.utils;

import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.HeaderResponse;
import com.obs.services.model.PutObjectRequest;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;

@Slf4j
@Data
@AllArgsConstructor
public class HaiweiOBSUtil {

    String endPoint;
    String ak;
    String sk;
    String bucketName;

   public String upload(byte[] bytes, String objectName){
       log.info("文件上传");

       try {
           ObsClient obsClient = new ObsClient(ak, sk,endPoint);
           // 文件上传
           // localfile 为待上传的本地文件路径，需要指定到具体的文件名
           PutObjectRequest request = new PutObjectRequest();
           request.setBucketName(bucketName);
           request.setObjectKey(objectName);
           obsClient.putObject(request);
           System.out.println("putObject successfully");
       } catch (ObsException e) {
           System.out.println("putObject failed");
           // 请求失败,打印http状态码
           System.out.println("HTTP Code:" + e.getResponseCode());
           // 请求失败,打印服务端错误码
           System.out.println("Error Code:" + e.getErrorCode());
           // 请求失败,打印详细错误信息
           System.out.println("Error Message:" + e.getErrorMessage());
           // 请求失败,打印请求id
           System.out.println("Request ID:" + e.getErrorRequestId());
           System.out.println("Host ID:" + e.getErrorHostId());
           e.printStackTrace();
       } catch (Exception e) {
           System.out.println("putObject failed");
           // 其他异常信息打印
           e.printStackTrace();
       }

       StringBuilder stringBuilder = new StringBuilder("https://");
       stringBuilder
               .append(bucketName)
               .append(".")
               .append(endPoint)
               .append("/")
               .append(objectName);

       log.info("文件上传到:{}", stringBuilder.toString());

       return stringBuilder.toString();
       //return null;
   }

}
